package com.uum.blog.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.uum.blog.pojo.entity.Comment;
import com.uum.blog.pojo.entity.CommentLike;
import com.uum.blog.service.CommentService;
import com.uum.blog.service.CommentLikeService;
import com.uum.blog.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Component
public class ScheduledTasks {

    @Autowired
    RedisService redisService;

    @Autowired
    CommentLikeService commentLikeService;

    @Autowired
    CommentService commentService;


    @Scheduled(cron = "0 0 2 * * ?")  //每天凌晨2点
//    @Scheduled(cron = "*/5 * * * * *")  //每5秒
    @Transactional
    public void saveLikeInSqlFromRedis() {
        //获取缓存中所有点赞数据
        Set<Map> set = redisService.listAllLike();
        System.out.println("执行定时任务的当前时间是=====》" + DateUtil.now());
        if (set.isEmpty()) {
            System.out.println("redis暂无数据，无须insert");
            return;
        }
        List<CommentLike> saveLikeList = new ArrayList<>();
        for (Map map : set) {
            String commentId = (String) map.get("commentId");
            commentId = commentId.substring(commentId.lastIndexOf(":") + 1);
            Set<Integer> userId = (Set) map.get("userId");
            for (Integer uId : userId) {
                CommentLike commentLike = new CommentLike();
                commentLike.setCommentId(Long.valueOf(commentId));
                commentLike.setUserId(Long.valueOf(uId));
//                likeService.save(commentLike);
                saveLikeList.add(commentLike);
            }
            commentService.update(new LambdaUpdateWrapper<Comment>().setSql("like_count = like_count + " + userId.size()).eq(Comment::getCommentId, commentId));
        }
        //更新点赞表数据
        commentLikeService.saveBatch(saveLikeList);
        //删除redis中的数据
        redisService.delAllLike();
    }
}
